import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;

/**
 * Write Thread is responsible for get local user input,
 * and send every input out.
 * 
 * @author weizhuowu
 */
public class WriteThread implements Runnable{

	UDPClient client;

	WriteThread(UDPClient c){
		this.client = c;		
	}

	@Override
	public void run() {

		BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in));
		String message = null;		

		if(UDPServer.class.equals(client.getClass())){
			System.out.println("Start writing to Group: "+client.getLocalIpAddress());
		}else{
			System.out.println("Start writing to Group: "+client.getServerAddr());
	    }
		
		while(true){	
			//Initialize
			message = null;
			//get user input message
			try {
				message = localReader.readLine();
			} catch (IOException e) {
				System.out.println("Oops, Readin Error!");
				e.printStackTrace();
			}
			//package and send message
			if(message!=null && (!message.isEmpty())){				

				if(UDPServer.class.equals(this.client.getClass())){//SERVER		
					message = client.getUserName()+": "+message;
					((UDPServer)client).broadcastMessage(message);				
				}else{//CLIENT
					DatagramPacket packetToSend = new DatagramPacket(message.getBytes(), message.getBytes().length, client.getServerAddr(), client.getServerPortNum());					
					try {
						client.getUDPSocket().send(packetToSend);						
					} catch (Exception e) {
						System.out.println("Oops, Package send failed!");
						e.printStackTrace();
					}
				}
			}           			
		}

	}


}
